package cn.lbd.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

public class Client {
    public static void main(String[] args) {
//        Selector selector = null;
        System.out.println("Client connected....");
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1",8765);
        SocketChannel channel = null;
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        try {
            //打开通道并连接
            channel = SocketChannel.open();
            channel.connect(inetSocketAddress);
            while (true){
                byte[] bytes = new byte[1024];
                System.in.read(bytes);
                //把数据放到缓冲区
                byteBuffer.put(bytes);
                //复位后，将缓冲区的数据在通道上写出
                byteBuffer.flip();
                channel.write(byteBuffer);
                //清空缓冲区数据
                byteBuffer.clear();

                int count = channel.read(byteBuffer);
                if (count == -1){
                    channel.close();
                    return;
                }
                byteBuffer.flip();
                byte[] bytes1 = new byte[byteBuffer.remaining()];
                byteBuffer.get(bytes1);
                String response = new String(bytes1).trim();
                System.out.println("Client：" + response);
                byteBuffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (channel != null){
                try {
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
